﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;

namespace BaseSet.Entity.Common.Xml
{
    /// <summary>
    /// XML相关操作
    /// </summary>
    public class XmlOper
    {
        ///// <summary>
        ///// 取XML节点
        ///// </summary>
        ///// <param name="xpath"></param>
        ///// <returns></returns>
        //public static XmlNodeList GetXmlNodes(string xpath)
        //{
        //    return new XmlNodeList();
        //}

        /// <summary>
        /// 读取XML文档
        /// </summary>
        /// <param name="filePath">文件相对于站点根目录的路径 如：App_Data/Config.xml</param>
        /// <returns></returns>
        public static XmlDocument GetXmlDocument(string filePath)
        {
            XmlDocument xd = new XmlDocument();
            string path = HttpContext.Current.Server.MapPath("~/" + filePath);
            try
            {
                xd.Load(path);
            }
            catch
            {
                throw new Exception("加载Xml失败！");
            }
            return xd;
        }

        /// <summary>
        ///  更改webconfig中节点的值
        /// </summary>
        /// <param name="nodeValue">更改的值</param>
        /// <param name="nodeName">结点名称</param>
        public static void UpdateConfig(string nodeName, string nodeValue)
        {
            // 这个是Web程序取站点路径 Winform取可执行文件路径 Application.ExecutablePath
            string configFile = HttpContext.Current.Server.MapPath("..\\Web.Config");
            XmlDocument doc = new XmlDocument();
            doc.Load(configFile);

            XmlNode node = doc.SelectSingleNode(@"//add[@key='" + nodeName + "']");
            XmlElement element = node as XmlElement;
            element.SetAttribute("value", nodeValue);

            doc.Save(configFile);
        }
    }
}
